package com.huluobo.lib_base.mvvm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.huluobo.lib_base.net.Const
import com.huluobo.lib_base.net.Res
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.Exception
import java.lang.RuntimeException

/**
 *  Created by LC on 2025/9/28.
 */
open class BaseViewModel : ViewModel() {

    val onFiled by lazy { MutableLiveData<Throwable>() }

    fun <T> executeNetwork(
        s: suspend () -> Res<T>,
        success: (T) -> Unit,
        failed: (Throwable) -> Unit = onFiled::postValue,
        okCode: Int = 200
    ) {
        viewModelScope.launch {
            try {
                val res = s.invoke()
                if (res.code == okCode) {
                    success(res.data)
                } else {
                    failed(RuntimeException(res.message))
                }
            } catch (e: Exception) {
                failed(e)
            }
        }
    }

    open fun mapToJson(map: Map<String, Any>): RequestBody {
        val json = Gson().toJson(map)
        return RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
    }
}